package com.zhongli.devplatform.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

@EnableSwagger2
@Configuration
public class SwaggerConfig implements WebMvcConfigurer {


@Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("**/swagger-ui.html")
        .addResourceLocations("classpath:/META-INF/resources/");
    registry.addResourceHandler("/webjars*")
        .addResourceLocations("classpath:/META-INF/resources/webjars/");
  }

  @Bean
  public Docket createExamTrainingRestApi() {

    /*
     * 配置全局参数 添加请求头
     */
    ParameterBuilder ticketPar = new ParameterBuilder();
    List<Parameter> pars = new ArrayList<Parameter>();
    ticketPar.name("Authorization").description("user token")
            .modelRef(new ModelRef("string")).parameterType("header")
            .required(false).build(); //header中的token参数非必填，传空也可以
    pars.add(ticketPar.build());

    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiExamTrainingInfo())
            .globalOperationParameters(pars)
            .select()
            //为当前包路径
            .apis(RequestHandlerSelectors.basePackage("com.zhongli.devplatform.controller"))
            //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
            .paths(PathSelectors.any())
            .build();
  }
  //构建 api文档的详细信息函数,注意这里的注解引用的是哪个
  private ApiInfo apiExamTrainingInfo() {
    return new ApiInfoBuilder()
            //页面标题
            .title("API文档")
            //创建人
            .contact(new Contact("chance", "", ""))
            //版本号
            .version("1.0")
            //描述
            .description("API 描述")
            .build();
  }

}
